package com.itsu.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itsu.dao.CourseDao;
import com.itsu.domain.Course;
import com.itsu.service.CourseService;
import com.itsu.utils.MapperUtils;

import java.util.List;

public class CourseServiceImpl implements CourseService {

    private CourseDao mapper;

    @Override
    public void save(Course course) {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            mapper.save(course);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void delete(Course course) {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            mapper.delete(course);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public void update(Course course) {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            mapper.update(course);
            MapperUtils.commit();
        } catch (Exception e) {
            MapperUtils.rollback();
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
    }

    @Override
    public Course findById(String id) {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            Course course = mapper.findById(id);
            return course;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public List<Course> findAll() {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            List<Course> all = mapper.findAll();
            return all;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }

    @Override
    public PageInfo<Course> findAll(int pageNum, int pageSize) {
        try {
            mapper = MapperUtils.getMapper(CourseDao.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Course> all = mapper.findAll();
            PageInfo<Course> coursePageInfo = new PageInfo<>(all);
            return coursePageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MapperUtils.close();
        }
        return null;
    }
}
